package com.gzbd.login.shiro.validator;


import com.gzbd.login.shiro.SystemSessionIdGenerator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 默认session校验器
 *
 * @author :ys
 * @date :2023-07-31 9:59
 */
@Component
public class DefaultSessionValidator implements SessionValidator {

    private final SessionDAO sessionDAO;


    public DefaultSessionValidator(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    /**
     * session 校验
     *
     * @param request HttpServletRequest 获取请求数据
     * @return 校验结果 true:通过 false:不通过
     */
    @Override
    public boolean checkSession(HttpServletRequest request) {
        //登录不校验session
        if (request.getRequestURI().contains("login")) {
            return true;
        }
        //省局不校验session
        Session current = SecurityUtils.getSubject().getSession(false);
        if (current != null) {
            Session cached = sessionDAO.readSession((Serializable) current.getAttribute(SystemSessionIdGenerator.SESSION_ID_KEY));
            if (cached == null || !current.getId().equals(cached.getId())) {
                return false;
            }
        }
        return true;
    }
}
